/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.fjs.liyq.entity;

import edu.fjs.liyq.service.ProductService;
import edu.fjs.liyq.service.impl.ProductServiceImpl;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 购物车
 * @author danny
 */
public class Cart implements Serializable {
    
    private List<CartItem> items = new ArrayList<>();
    private User user;

    /**
     * @return the items
     */
    public List<CartItem> getItems() {
        return items;
    }

    /**
     * @param items the items to set
     */
    public void setItems(List<CartItem> items) {
        this.items = items;
    }

    /**
     * @return the user
     */
    public User getUser() {
        return user;
    }

    /**
     * @param user the user to set
     */
    public void setUser(User user) {
        this.user = user;
    }

    /**
     * @return the cost
     */
    public double getCost() {
        double cost = 0;
        for (CartItem item : items) {
            Product p = item.getProduct();
            if (p != null)
                cost += p.getEpPrice() * item.getQuantity();
        }
        return cost;
    }
    
    public boolean delete(long productId) {
        // 查找到购物车条目
        for (CartItem item : items) {
            Product p = item.getProduct();
            if (p != null && p.getEpId() == productId) {
                return items.remove(item);
            }
        }
        return false;
    }
    
    public void add(Product prod) {
        CartItem ci = new CartItem();
        ci.setProduct(prod);
        if (items.contains(ci)) {
            CartItem item = items.get(items.indexOf(ci));
            item.add(1);
        } else {
            CartItem item = new CartItem();
            item.setProduct(prod);
            item.setQuantity(1);
            items.add(item);
        }
    }
    
    public static void main(String[] args) {
        ProductService service = new ProductServiceImpl();
        Product p1 = service.getById(591L);
        Product p2 = service.getById(591L);
        System.out.println(p1 == p2);
        System.out.println(p1.equals(p2));
    }
}
